package com.bobo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bobo.auth.common.Result;
import com.bobo.auth.config.WebMvcConfig;
import com.bobo.domain.SysUser;
import com.bobo.domain.SysUserRole;
import com.bobo.service.SysUserRoleService;
import com.bobo.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@RequestMapping("user")
@RestController
public class UserController {
    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysUserRoleService sysUserRoleService;

    @Autowired
    RedisTemplate redisTemplate;


    @RequestMapping("edit")
    public Result edit(@RequestBody SysUser sysUser){
        boolean b = sysUserService.saveOrUpdate(sysUser);
        return b?Result.success():Result.fail();

    }


    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
  //  @PreAuthorize("permitAll()")
    @RequestMapping("upFile")
    public Result upFile(MultipartFile file) throws IOException {
        if(null!=file &&!file.isEmpty()){//有文件
            String  path= WebMvcConfig.uploadRealPath;//文件上传地址
            String oName = file.getOriginalFilename();//原始文件名称 a.jpg
            String filename = UUID.randomUUID()+oName.substring(oName.lastIndexOf("."));//防止文件重名
            File file1 = new File(path, filename);//在硬盘创建一个新的文件
            file.transferTo(file1);//文件写入硬盘
            return Result.success("pic/"+filename);//返回文件的虚拟路径
        }
        return Result.fail(500,"请选择上传文件");
    }

    /**
     * 绑定用户角色
     * @param sysUserRole
     * @return
     */
   // @PreAuthorize("hasRole('ROLE_ADMIN')") //
    @RequestMapping("bindRole")
    public Result bindRole(@RequestBody  SysUserRole sysUserRole){

      boolean b=  sysUserService.bindRole(sysUserRole);
       return b?Result.success():Result.fail();


    }

    /**
     * 用户list
     * @param page
     * @param sysUser
     * @return
     */
    @RequestMapping("list")
    public Result list(Page page, SysUser sysUser ){
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(ObjectUtils.isNotEmpty(sysUser.getUsername()),SysUser::getUsername,sysUser.getUsername());
        Page page1 =null;
        Boolean aBoolean = false;// 本月不用 redisTemplate.hasKey("userList");
        if(aBoolean){//如果redis 有则redis获取
            page1= (Page) redisTemplate.opsForValue().get("userList");
            System.out.println("从redis获取");
        }else {//redis没有则从数据库获取
            page1 = sysUserService.page(page, wrapper);
            redisTemplate.opsForValue().set("userList",page1);
            System.out.println("从数据库获取");
        }

        return Result.success(page1);
    }

    @PostMapping("add")
    public boolean add(@RequestBody  SysUser sysUser){//@RequestBody json 转为java
       return  sysUserService.save(sysUser);
    }

    @RequestMapping("getRoleByUid")
    public Result getRoleByUid(Integer id){
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUid,id);

        //获取用户拥有角色对象
        List<SysUserRole> roles = sysUserRoleService.list(queryWrapper);

        ArrayList<Integer> list = new ArrayList<>();
        //遍历对象获取角色id
        if(null!=roles && roles.size()>0) {
            for (SysUserRole role : roles) {
                list.add(role.getRid());
            }
        }
        return Result.success(list);
    }
}
